<template>
  <el-dialog
    v-model="visible"
    :title="!dataForm.faceBaseId ? '新增人脸底图' : '修改人脸底图'"
    :close-on-click-modal="false"
    width="600px"
  >
    <el-form
      ref="dataFormRef"
      :model="dataForm"
      :rules="dataRule"
      label-width="100px"
      @keyup.enter="onSubmit()"
    >
      <el-form-item label="人脸名称" prop="faceName">
        <el-input
          v-model="dataForm.faceName"
          placeholder="请输入人脸名称"
          maxlength="50"
          show-word-limit
          clearable
        />
      </el-form-item>

      <!-- <el-form-item label="人脸类型" prop="faceType">
        <el-radio-group v-model="dataForm.faceType">
          <el-radio :label="1">男性</el-radio>
          <el-radio :label="2">女性</el-radio>
          <el-radio :label="3">通用</el-radio>
        </el-radio-group>
      </el-form-item> -->

      <el-form-item label="人脸图片" prop="faceImageUrl">
        <pic-upload v-model="dataForm.faceImageUrl" />
      </el-form-item>

      <!-- <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="缩放比例" prop="scale">
            <el-input-number
              v-model="dataForm.scale"
              :min="0.1"
              :max="3.0"
              :step="0.1"
              :precision="2"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="旋转角度" prop="rotation">
            <el-input-number
              v-model="dataForm.rotation"
              :min="-360"
              :max="360"
              :step="1"
              :precision="1"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="X轴偏移" prop="offsetX">
            <el-input-number
              v-model="dataForm.offsetX"
              :min="-100"
              :max="100"
              :step="1"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="Y轴偏移" prop="offsetY">
            <el-input-number
              v-model="dataForm.offsetY"
              :min="-100"
              :max="100"
              :step="1"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row> -->

      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="dataForm.status">
          <el-radio :label="1">启用</el-radio>
          <el-radio :label="0">禁用</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="visible = false"> 取消 </el-button>
        <el-button type="primary" @click="onSubmit()"> 确定 </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { Plus } from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from "element-plus";
import $cookie from "vue-cookies";

const emit = defineEmits(["refreshDataList"]);

const visible = ref(false);
const dataFormRef = ref(null);
const dataForm = reactive({
  faceBaseId: 0,
  faceName: "",
  faceType: 3,
  faceImageUrl: "",
  scale: 1.0,
  offsetX: 0,
  offsetY: 0,
  rotation: 0.0,
  status: 1,
});

const dataRule = {
  faceName: [
    { required: true, message: "人脸名称不能为空", trigger: "blur" },
    {
      min: 1,
      max: 50,
      message: "人脸名称长度不能超过50个字符",
      trigger: "blur",
    },
  ],
  faceType: [{ required: true, message: "请选择人脸类型", trigger: "change" }],
  faceImageUrl: [
    { required: true, message: "请上传人脸图片", trigger: "change" },
  ],
  scale: [{ required: true, message: "缩放比例不能为空", trigger: "blur" }],
  status: [{ required: true, message: "请选择状态", trigger: "change" }],
};

// 上传配置
const uploadUrl = http.adornUrl("/file/upload");
const uploadHeaders = reactive({
  Authorization: $cookie.get("Authorization"),
});

const init = (val) => {
  visible.value = true;
  nextTick(() => {
    dataFormRef.value?.resetFields();
    if (val) {
      // 获取详情
      http({
        url: http.adornUrl(`/admin/faceBase/info/${val.faceBaseId}`),
        method: "get",
        params: http.adornParams(),
      }).then(({ data }) => {
        Object.assign(dataForm, data);
      });
    } else {
      // 重置表单
      Object.assign(dataForm, {
        faceBaseId: 0,
        faceName: "",
        faceType: 3,
        faceImageUrl: "",
        scale: 1.0,
        offsetX: 0,
        offsetY: 0,
        rotation: 0.0,
        status: 1,
      });
    }
  });
};

defineExpose({ init });

/**
 * 表单提交
 */
const onSubmit = () => {
  dataFormRef.value?.validate((valid) => {
    if (!valid) {
      return;
    }

    const url = dataForm.faceBaseId ? "/admin/faceBase" : "/admin/faceBase";
    const method = dataForm.faceBaseId ? "put" : "post";

    http({
      url: http.adornUrl(url),
      method: method,
      data: http.adornData({
        faceBaseId: dataForm.faceBaseId || undefined,
        faceName: dataForm.faceName,
        faceType: 3,
        faceImageUrl: dataForm.faceImageUrl,
        scale: dataForm.scale,
        offsetX: dataForm.offsetX,
        offsetY: dataForm.offsetY,
        rotation: dataForm.rotation,
        status: dataForm.status,
      }),
    }).then(() => {
      ElMessage({
        message: "操作成功",
        type: "success",
        duration: 1500,
        onClose: () => {
          visible.value = false;
          emit("refreshDataList");
        },
      });
    });
  });
};

/**
 * 上传成功处理
 */
const handleUploadSuccess = (response) => {
  if (response && response.code === 0) {
    dataForm.faceImageUrl = response.url || response.data;
    ElMessage.success("上传成功");
  } else {
    ElMessage.error(response?.msg || "上传失败");
  }
};

/**
 * 上传前检查
 */
const beforeUpload = (file) => {
  const isImage = file.type.startsWith("image/");
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isImage) {
    ElMessage.error("只能上传图片文件!");
    return false;
  }
  if (!isLt2M) {
    ElMessage.error("图片大小不能超过 2MB!");
    return false;
  }
  return true;
};

/**
 * 预览图片
 */
const previewImage = () => {
  if (dataForm.faceImageUrl) {
    window.open(dataForm.faceImageUrl, "_blank");
  }
};

/**
 * 删除图片
 */
const removeImage = () => {
  ElMessageBox.confirm("确定要删除这张图片吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      dataForm.faceImageUrl = "";
      ElMessage.success("删除成功");
    })
    .catch(() => {});
};
</script>

<style scoped lang="scss">
.upload-container {
  display: flex;
  align-items: center;
}

.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);

  &:hover {
    border-color: var(--el-color-primary);
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 120px;
    height: 120px;
    text-align: center;
    line-height: 120px;
  }
}

.avatar-container {
  position: relative;
  display: inline-block;

  .avatar {
    width: 120px;
    height: 120px;
    border-radius: 6px;
    border: 1px solid #ebeef5;
  }

  .avatar-actions {
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    background: rgba(0, 0, 0, 0.5);
    padding: 4px;
    text-align: center;
    border-radius: 0 0 6px 6px;

    .el-button {
      margin: 0 2px;
      padding: 2px 6px;
      font-size: 12px;
    }
  }
}
</style>
